const webpack = require('webpack');
const path = require('path');
const fs = require('fs');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');

const NODE_ENV = process.env.NODE_ENV; // 该环境变量提供给依赖包使用
const BACKEND_ENV = process.env.BACKEND_ENV; // 后台服务器环境
const pages = fs.readdirSync('./src/pages');

console.log('NODE_ENV = ', NODE_ENV);
console.log('BACKEND_ENV = ', BACKEND_ENV);

module.exports = {

  mode: NODE_ENV,

  devtool: NODE_ENV == 'development' && 'eval-cheap-module-source-map',

  entry: pages.reduce((pre, cur) => {
    pre[cur] = './src/pages/' + cur + '/index.js';
    return pre;
  }, {}),

  output: {
    filename: `js/[name]${NODE_ENV == 'development' ? '' : '.[chunkhash:7]'}.js`, // 模块热替换不能使用chunkhash，而且webpack-dev-server也无需使用hash
    path: path.resolve(__dirname, 'dist'),
    clean: true,
  },

  module: {
    rules: [
      {
        test: /\.m?js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: [
              ['@babel/preset-env', { targets: 'defaults' }]
            ],
            plugins: [
              // '@babel/plugin-proposal-class-properties',
            ],
          }
        }
      },
      {
        test: /\.css$/i,
        include: path.resolve(__dirname, './src/plugins'),
        use: [
          'style-loader',
          {
            loader: 'css-loader',
            options: {
              modules: {
                localIdentName: '[local]-[hash:base64:5]'
              },
            },
          },
          'postcss-loader',
        ]
      },
      {
        test: /\.css$/i,
        exclude: path.resolve(__dirname, './src/plugins'),
        use: ['style-loader', 'css-loader', 'postcss-loader'],
      },
      {
        test: /\.(html)$/,
        loader: 'html-loader',
        include: path.resolve(__dirname, './src/plugins'),
        options: {
          minimize: true, // 压缩
          esModule: false,
        }
      },
      {
        test: /\.(png|jpe?g|gif|svg|ttf|eot|woff|woff2|webm|mp3)$/,
        loader: 'file-loader',
        options: {
          publicPath: '/',
          name: 'asset/[name].[ext]?v=[contenthash:7]',
          esModule: false,
        }
      },
    ],
  },

  resolve: {
    extensions: ['.js', '.json'],
    alias: {
      plugins: path.resolve(__dirname, './src/plugins/'),
      utils: path.resolve(__dirname, './src/utils/'),
      assets: path.resolve(__dirname, './src/assets/'),
    },
  },

  plugins: [
    new webpack.DefinePlugin({
      'BACKEND_ENV': JSON.stringify(BACKEND_ENV),
    }),
    new CopyWebpackPlugin({
      patterns: [
        {
          from: './public',
          globOptions: {
            ignore: ['index.html'],
          },
        },
      ],
    }),
    ...pages.map(page => {
      var template = './src/pages/' + page + '/index.html';
      if (!fs.existsSync(template)) {
        template = './public/index.html';
      }
      return new HtmlWebpackPlugin({
        filename: page + '.html',
        template,
        chunks: [page],
        inject: 'body',
      });
    }),
  ],

  devServer: {
    contentBase: './dist',
    open: true,
    openPage: 'links.html',
    host: '0.0.0.0',
    useLocalIp: true,
    // proxy: [{
    //   context: ['/favicon.ico', '/asset', '/tmp'],
    //   target: 'https://ylmnewtst.mao-app.com',
    //   secure: false,
    //   changeOrigin: true, // 设置为true时，下面的headers设置才会生效
    //   headers: { // 确保headers里面所有的key全部小写
    //     host: 'ylmnewtst.mao-app.com',
    //     referer: 'https://ylmnewtst.mao-app.com/test.html'
    //   }
    // }, { // api接口反向到测试服
    //   context: '/apiTesting',
    //   target: 'https://newapidev.mao-app.com',
    //   pathRewrite: { "^/apiTesting": "" },
    //   secure: false,
    //   changeOrigin: true,
    //   headers: {
    //     host: 'ylmnewtst.mao-app.com',
    //     referer: 'https://ylmnewtst.mao-app.com/test.html'
    //   }
    // }, { // api接口反向到正式服
    //   context: '/apiOfficial',
    //   target: 'https://cca.mao-app.com',
    //   pathRewrite: { "^/apiOfficial": "" },
    //   secure: false,
    //   changeOrigin: true,
    //   headers: {
    //     host: 'cc.mao-app.com',
    //     referer: 'https://cc.mao-app.com/test.html'
    //   }
    // }]
  },

  optimization: NODE_ENV == 'development' ? {} : {
    splitChunks: {
      chunks: 'all',
      name: (module, chunks, cacheGroupKey) => {
        let filename = path.relative(__dirname, module.request);
        filename = filename.split('.')[0].replace(/[/\\]+/g, '~');
        // console.log(filename);
        return filename;
      },
    },
    // runtimeChunk: 'single',
  },
};